package com.nondo.dean.order.controller.api.app;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.nondo.dean.common.annotation.ApiVersion;
import com.nondo.dean.common.tool.ValidateUtil;
import com.nondo.dean.common.web.Page;
import com.nondo.dean.common.web.Query;
import com.nondo.dean.common.web.View;
import com.nondo.dean.order.common.Constant;
import com.nondo.dean.order.common.OrderTip;
import com.nondo.dean.order.domain.OrderSubject;
import com.nondo.dean.order.model.param.AppOrderParam;
import com.nondo.dean.order.model.result.AppOrderResult;
import com.nondo.dean.order.service.OrderService;
import com.nondo.dean.order.service.UserService;

/**
 * 订单管理APP接口
 * @author zlj
 * @date 2018年4月18日
 */
@RestController("apiAppOrder")
@RequestMapping("/{v}/app/order")
public class OrderController {
    
    
    @Autowired
    OrderService orderService;
    
    @Autowired
    UserService userService;
    
    /**
     * 查看订单详情
     * @param request
     * @param response
     * @param id
     * @return
     */
    @ApiVersion(1)
    @RequestMapping("/info/{id}")
    public View<AppOrderResult> info(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Integer id) {
        View<AppOrderResult> view = new View<AppOrderResult>(20000, "获取数据成功");
        
        AppOrderResult orderResult = new AppOrderResult();
        if (id != null) {
            Integer userId = userService.getLoginUserId();
            OrderSubject order = orderService.selectOrder(id);
            if (order != null && (order.getUserId() == userId.intValue())) {
                orderResult = orderService.getAppOrderResult(order);
            } else {
                return View.ofParamsError(OrderTip.ORDER_NOT_FOUND);
            }
        }

        view.setData(orderResult);
        return view;
    }
    
    /**
     * 生成订单
     * @param request
     * @param response
     * @param order 订单信息 {@link OrderSubject}
     * @return
     */
    @ApiVersion(1)
    @RequestMapping("/add")
    public View<OrderSubject> createOrder(HttpServletRequest request, HttpServletResponse response,
            @Validated @RequestBody AppOrderParam orderParam, BindingResult result) {
        View<OrderSubject> view = new View<OrderSubject>(20000, "添加成功");

        if (result.hasErrors()) {
            view.setCode(40000);
            view.setMessage(ValidateUtil.first(result.getAllErrors()));
        } else {
            String message = AppOrderParam.checkInputParam(orderParam);
            if (message != null) {
                return View.ofParamsError(message);
            }
            this.orderService.createAppOrder(orderParam);
        }
        return view;
    }

    /**
     * 获取订单分页查询列表
     * @param request
     * @param response
     * @param query
     * @return
     */
    @ApiVersion(1)
    @RequestMapping("/list")
    public View<Page<AppOrderResult>> list(HttpServletRequest request, HttpServletResponse response, @RequestBody Query<OrderSubject> query) {
        View<Page<AppOrderResult>> view = new View<Page<AppOrderResult>>(20000, "获取列表成功");

        OrderSubject order = query.getData();
        
        Integer userId = userService.getLoginUserId();
        if (order == null) {
            order = new OrderSubject();
        }

        order.setUserId(userId);
        
        Page<AppOrderResult> page = new Page<AppOrderResult>(query.getPage(), query.getSize(), orderService.count(order));
        
        List<OrderSubject> orderList = orderService.getOrderList(query.getOffset(), query.getLimit(), order);
        
        List<AppOrderResult> orderResultList = new ArrayList<AppOrderResult>();
        
        for (OrderSubject orderSubject : orderList) {
            AppOrderResult orderResult = orderService.getAppOrderResult(orderSubject);
            orderResultList.add(orderResult);
        }
        
        page.setContent(orderResultList);
        
        view.setData(page);
        
        return view;
    }

    /**
     * 取消订单
     * @param request
     * @param response
     * @param id
     * @return
     */
    @ApiVersion(1)
    @SuppressWarnings("rawtypes")
    @RequestMapping("/cancel/{id}")
    public View cancel(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Integer id) {
        View view = new View(20000, "取消成功");
        Integer userId = userService.getLoginUserId();
        OrderSubject order = orderService.selectOrder(id);
        if (order.getUserId() == userId.intValue()) {
            order.setOrderStatus(Constant.HAVE_BEEN_CANCELED);;
            this.orderService.cancelOrder(order);
        } else {
            return View.of401Error(OrderTip.ORDER_NOT_FOUND);
        }

        return view;
    }
    
    /**
     * 确认收货
     * @param request
     * @param response
     * @param id
     * @return
     */
    @ApiVersion(1)
    @SuppressWarnings("rawtypes")
    @RequestMapping("/receive/{id}")
    public View receive(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Integer id) {
        View view = new View(20000, "确认收货成功");
        Integer userId = userService.getLoginUserId();
        OrderSubject order = orderService.selectOrder(id);
        if (order.getUserId() == userId.intValue()) {
            order.setOrderStatus(Constant.HAVE_BEEN_COMPLETED);;
            this.orderService.confirmReceive(order);
        } else {
            return View.of401Error(OrderTip.ORDER_NOT_FOUND);
        }

        return view;
    }
    
    /**
     * 重新购买
     * @param request
     * @param response
     * @param id
     * @return
     */
    @ApiVersion(1)
    @SuppressWarnings("rawtypes")
    @RequestMapping("/rebuy/{id}")
    public View reBuy(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Integer id) {
        View view = new View(20000, "下单成功");
        Integer userId = userService.getLoginUserId();
        OrderSubject order = orderService.selectOrder(id);
        if (order.getUserId() == userId.intValue()) {
            if (order.getOrderStatus() == Constant.HAVE_BEEN_CANCELED) {
                order.setOrderStatus(Constant.WAITING_TO_PAY);;
                this.orderService.reBuy(order);
            }
        } else {
            return View.of401Error(OrderTip.ORDER_NOT_FOUND);
        }

        return view;
    }
}